import xbmcplugin
import xbmcgui
import xbmcaddon

import os
import threading
import urllib, urllib2

from xml.etree.ElementTree import XML, fromstring, tostring

RSS_FEED = 'http://feeds.tvo.org/tvo/TxZN?format=xml'
itunes = '{http://www.itunes.com/dtds/podcast-1.0.dtd}'
yahoo = '{http://search.yahoo.com/mrss/}'

pluginhandle = int(sys.argv[1])
__settings__ = xbmcaddon.Addon(id='plugin.video.tvo.theagenda')
home = __settings__.getAddonInfo('path')
icon = xbmc.translatePath( os.path.join( home, 'icon.png' ) )
fanart = xbmc.translatePath( os.path.join( home, 'fanart.jpg' ) )
fanart2 = xbmc.translatePath( os.path.join( home, 'fanart2.jpg' ) )


################################################################################
# menus / episode listings

def home():
        addDir('All Episodes', "", "allEpisodes", "")
        addDir('Latest Episodes', "", "latestEpisodes", "")
        addDir('Week In Review', "", "weekInReviewEpisodes", "")
        addDir('Search', "", "search", "")

def allEpisodes(tree):
	for child in tree.getiterator('item'):
		addEpisodeToList(child)
		
def latestEpisodes(tree, num):
	count = 0	
	for child in tree.getiterator('item'):
		addEpisodeToList(child)
		count  += 1
		if count >= num:
			return

def weekInReviewEpisodes(tree):
	UsearchTerm = "WEEK IN REVIEW"
	for child in tree.getiterator('item'):
		if isRelevantEpisode(child, UsearchTerm):
			addEpisodeToList(child)

def searchEpisodes(tree, searchTerm):
	UsearchTerm = searchTerm.upper()	
	for child in tree.getiterator('item'):
		if isRelevantEpisode(child, UsearchTerm):
			addEpisodeToList(child)

################################################################################
# RSS retreival and parsing

def readRSS():
        req = urllib2.Request(RSS_FEED)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
        response = urllib2.urlopen(req)
        rssxml=response.read()
        response.close()
        #print rssxml
        return fromstring(rssxml)	# return the parsed element tree

def addEpisodeToList(child):
	info = parseEpisodeInfo(child)
	listEpisode(info)

def parseEpisodeInfo(child):
	title = child.find('title').text
	summary = child.find(itunes + 'summary').text
	duration = child.find(itunes + 'duration').text
	thumbnailUrl = child.find(yahoo + 'thumbnail').attrib['url']
	mp4url = child.find(yahoo + 'content').attrib['url']
	date = child.find('pubDate').text	
	#print 'title: ' + title
	#print 'summary: ' + summary
	#print 'duration: ' + duration
	#print 'date: ' + date
	#print 'thumbnail: ' + thumbnailUrl
	#print 'mp4: ' + mp4url
	#print '----------------------------------------------------------------------'	
	return {'description':summary, 'name':title, 'mp4url':mp4url, 'date':date,'duration':duration,'thumbnailUrl':thumbnailUrl}

def listEpisode(info):
	description = info['description'] + ' \n\n' + info['date']
	liz=xbmcgui.ListItem(info['name'], iconImage=info['thumbnailUrl'], thumbnailImage=info['thumbnailUrl'])
	liz.setInfo( type="Video", infoLabels={ "Title": info['name'],"Plot":description, "Duration":info['duration'] } )
	liz.setProperty( "Fanart_Image", fanart2 )
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=info['mp4url'],listitem=liz)

def isRelevantEpisode(child, searchTerm):
	if child.find('title').text.upper().find(searchTerm) > -1:
		return True	
	if child.find(itunes + 'subtitle').text.upper().find(searchTerm) > -1:
		return True	
	if child.find(itunes + 'summary').text.upper().find(searchTerm) > -1:
		return True
	if child.find('description').text.upper().find(searchTerm) > -1:
		return True		
	if child.find(itunes + 'keywords').text.upper().find(searchTerm) > -1:
		return True	
	return False

################################################################################
# utils (thanks howstuffworks addon)

def parameters_string_to_dict(parameters):
        ''' Convert parameters encoded in a URL to a dict. '''
        paramDict = {}
        if parameters:
            paramPairs = parameters[1:].split("&")
            for paramsPair in paramPairs:
                paramSplits = paramsPair.split('=')
                if (len(paramSplits)) == 2:
                    paramDict[paramSplits[0]] = paramSplits[1]
        return paramDict

def addDir(name,url,mode,iconimage):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "Title": name } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
        return ok

def getUserInput():
        keyboard = xbmc.Keyboard('', 'Search')
        keyboard.doModal()
        if keyboard.isConfirmed() and keyboard.getText():
          return keyboard.getText()
        else:
          return ''

################################################################################
# threading	- see: http://www.artfulcode.net/articles/multi-threading-python/

class RssGetter(threading.Thread):
    def __init__(self):
        self.result = None
        threading.Thread.__init__(self)
    def get_result(self):
        return self.result
    def run(self):
        self.result = readRSS()

################################################################################


params=parameters_string_to_dict(sys.argv[2])
mode=params.get('mode')

if mode == 'allEpisodes':
    allEpisodes(readRSS())
elif mode == 'latestEpisodes':
    latestEpisodes(readRSS(), 10)
elif mode == 'weekInReviewEpisodes':
    weekInReviewEpisodes(readRSS())
elif mode == 'search':
    rssThread = RssGetter()
    rssThread.start()	# start getting rss info while user is typing in what they want
    searchTerm = getUserInput()
    if len(searchTerm) > 0:        
        rssThread.join()	# wait for rss parsing to finish
        tree = rssThread.get_result()
        searchEpisodes(tree, searchTerm)
    else:
        if rssThread.isAlive():
            try:
                rssThread._Thread__stop()
            except:
                print 'unable to stop rssThread'
else:
    home()

xbmcplugin.endOfDirectory(pluginhandle)